package com.hcb.micro.controller;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.hcb.micro.dto.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hcb.micro.controller.base.BaseControllers;
import com.hcb.micro.service.ICashRedLogService;
import com.hcb.micro.service.IMallService;
import com.hcb.micro.service.IOrderProductRefundService;
import com.hcb.micro.service.IOrderProductService;
import com.hcb.micro.service.IOrderService;
import com.hcb.micro.service.IProductSellerService;
import com.hcb.micro.service.IProductService;
import com.hcb.micro.service.IQqbsAccountService;
import com.hcb.micro.service.IQqbsFansOrderService;
import com.hcb.micro.service.IQqbsRewardService;
import com.hcb.micro.service.IQqbsWithdrawalsLogService;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("sellerReward")
public class SellerRewardController extends BaseControllers{
	
	@Autowired
	IQqbsAccountService qqbsAccountService;
	
	@Autowired
	IMallService mallService;
	
	@Autowired
	IProductSellerService productSellerService;
	
	@Autowired
	IOrderService orderService;
	
	@Autowired
	IOrderProductService orderProductService;
	
	@Autowired
	IProductService productService;
	
	@Autowired
	IOrderProductRefundService orderProductRefundService;
	
	@Autowired
	IQqbsFansOrderService qqbsFansOrderService;
	
	@Autowired
	ICashRedLogService cashRedLogService;
	
	@Autowired
	IQqbsWithdrawalsLogService qqbsWithdrawalsLogService;
	
	@Autowired
	IQqbsRewardService qqbsRewardService;

	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public String list() {
		JSONObject json = new JSONObject();
		if (sign == 1) {
			json.put("result", "1");
			json.put("description", "请检查参数格式是否正确或者参数是否完整");
			return buildReqJsonInteger(1, json);
		}
		// 登录认证失败
		if (sign == 2) {
			json.put("result", "2");
			json.put("description", "账号未登录");
			return buildReqJsonInteger(2, json);
		}
		
		HttpSession session = request.getSession();
		Manager manager = (Manager) session.getAttribute("MANAGER");
        if(manager == null){
        	json.put("result", "1");
			json.put("description", "账号未登陆");
			return buildReqJsonObject(json);
        }
		
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		
		Map<String,Object> para = new HashMap<>();
		
		if(manager.getType() == 3){
			para.put("productSellerId", manager.getProductSellerId());
		}
		
		if (bodyInfo.get("productSellerId") != null && !"".equals(bodyInfo.get("productSellerId"))) {
			para.put("productSellerId", bodyInfo.getString("productSellerId"));
		}
		if (bodyInfo.get("name") != null && !"".equals(bodyInfo.get("name"))) {
			para.put("name", bodyInfo.getString("name"));
		}
		
		List<ProductSeller> productSellerAllList = productSellerService.selectAllByPara(para);
		
		if(bodyInfo.get("page") != null && !"".equals(bodyInfo.get("page"))) {
			para.put("start", (Integer.valueOf(bodyInfo.getString("page"))-1)*Integer.valueOf(bodyInfo.getString("pageSize")));
		}
		if(bodyInfo.get("pageSize") != null && !"".equals(bodyInfo.get("pageSize"))) {
			para.put("size", Integer.valueOf(bodyInfo.getString("pageSize")));
		}
		List<ProductSeller> productSellerList = productSellerService.selectAllByPara(para);
		
		if(productSellerList.size() <= 0){
			json.put("result", "1");
			json.put("description", "供应商列表不存在");
			return buildReqJsonObject(json);
		}
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<Map<String,Object>> list = new ArrayList<>();
		for(ProductSeller productSeller:productSellerList){
			Map<String,Object> map = new HashMap<>();
			
			map.put("id", productSeller.getId()+"");
			map.put("name", productSeller.getName()+"");
			map.put("company", productSeller.getCompany()==null?"":productSeller.getCompany());
			map.put("address", productSeller.getAddress()==null?"":productSeller.getAddress());
			map.put("undertakeCount", productSeller.getUndertakeCount()==null?"":productSeller.getUndertakeCount());
			map.put("logo", productSeller.getLogo()==null?"":productSeller.getLogo());
			map.put("status", productSeller.getStatus());
			map.put("createTime", productSeller.getCreateTime()==null?"":sdf.format(productSeller.getCreateTime()));
			list.add(map);
		}
		
    	json.put("result", "0");
		json.put("description", "获取供应商列表成功");
		json.put("list", list);
		json.put("count", productSellerAllList.size());
		return buildReqJsonObject(json);
	}
	
	@RequestMapping(value = "orderList", method = RequestMethod.POST)
	@ResponseBody
	public String orderList() {
		JSONObject json = new JSONObject();
		if (sign == 1) {
			json.put("result", "1");
			json.put("description", "请检查参数格式是否正确或者参数是否完整");
			return buildReqJsonInteger(1, json);
		}
		// 登录认证失败
		if (sign == 2) {
			json.put("result", "2");
			json.put("description", "账号未登录");
			return buildReqJsonInteger(2, json);
		}
		
		HttpSession session = request.getSession();
		Manager manager = (Manager) session.getAttribute("MANAGER");
        if(manager == null){
        	json.put("result", "1");
			json.put("description", "账号未登陆");
			return buildReqJsonObject(json);
        }
		
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		
		Map<String,Object> para = new HashMap<>();
		if (bodyInfo.get("orderId") != null && !"".equals(bodyInfo.get("orderId"))) {
			para.put("orderId", bodyInfo.getString("orderId"));
		}
		if(bodyInfo.get("accountId") != null && !"".equals(bodyInfo.get("accountId"))) {
			para.put("accountId", bodyInfo.getString("accountId"));
		}
		if(bodyInfo.get("status") != null && !"".equals(bodyInfo.get("status"))) {
			para.put("status", bodyInfo.getString("status"));
		}
		
		if(bodyInfo.get("sellerId") != null && !"".equals(bodyInfo.get("sellerId"))) {
			para.put("productSellerId", bodyInfo.getString("sellerId"));
		}
		
		Mall mall = mallService.selectByMallUuid(manager.getMallUuid()); 
		if(mall != null && !"商盟惠购".equals(mall.getMallName())){
			para.put("mallUuid", mall.getMallUuid());
		}
		
		List<Order> orderListAll = orderService.selectByPara(para);
		
		if(bodyInfo.get("page") != null && !"".equals(bodyInfo.get("page"))) {
			para.put("start", (Integer.valueOf(bodyInfo.getString("page"))-1)*Integer.valueOf(bodyInfo.getString("pageSize")));
		}
		if(bodyInfo.get("pageSize") != null && !"".equals(bodyInfo.get("pageSize"))) {
			para.put("size", Integer.valueOf(bodyInfo.getString("pageSize")));
		}
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		List<Order> orderList = orderService.selectByPara(para);
		
		if(orderList.size() <= 0){
			json.put("result", "1");
			json.put("description", "没有订单信息！");
			return buildReqJsonObject(json);
		}
		List<Map<String,Object>> list = new ArrayList<>();
		for(Order order:orderList){
			Map<String,Object> map = new HashMap<>();
			Mall orderMall = mallService.selectByMallUuid(order.getMallUuid());
			
			QqbsAccount account = qqbsAccountService.selectByAccountId(order.getAccountId());
			
			ProductSeller ps = productSellerService.selectByPrimaryKey(order.getSellerId());
			
			map.put("id", order.getId()+"");
			map.put("number", order.getNumber()+"");
			map.put("mallName", orderMall.getMallName()+"商城");
			map.put("sellerName", ps== null?"":ps.getName());
			map.put("accountId", order.getAccountId()+"");
			map.put("realPrice", order.getRealPrice()+"");
			if(account!=null){
				map.put("accountNickName", account.getNickname()==null?"":account.getNickname());				
			}else{
				map.put("accountNickName", "");
			}
			
			//订单状态；1：未付款，2：待发货，3：已发货，4：交易成功，5：用户取消（待退款团购），6：超时取消（已退款团购），7：团购进行中(团购)
			String status = "";
			switch(order.getStatus()){
			case 1:
				status = "未付款";
				break;
			case 2:
				status = "已支付,待发货";
				break;
			case 3:
				status = "已发货";
				break;
			case 4:
				status = "交易成功";
				break;
			case 5:
				status = "用户取消";
				break;
			}
			
			List<OrderProductRefund> oprList = orderProductRefundService.selectByOrderId(order.getId());
			if(oprList.size()>0){
				status = "退款订单";
			}
			
			map.put("status", status);
			
			//商品类别（0.非通信类;1.通信类）
			List<OrderProduct> opList	= orderProductService.selectByOrderId(order.getId());
			Map<String,Object> productPara = new HashMap<>();
			productPara.put("productId", opList.get(0).getProductId());
			List<Product> product = productService.selectByPara(productPara);
			String productType = "商品已下架";
			if(product.size()>0){
				switch(product.get(0).getType()){
				case 0:
					productType = "普通商品";
					break;
				case 1:
					productType = "套餐商品";
					break;
				}
			}
			
			map.put("productType", productType);
			
			String operationStatusValue = "不可提现";
			if(order.getStatus() == 4){
				if(order.getOperationStatus() == 1){
					operationStatusValue = "已提现";
				}else{
					operationStatusValue = "未提现";
				}
			}else{
				if(order.getOperationStatus() == 1){
					operationStatusValue = "已提现";
				}
			}
			
			map.put("operationStatusValue", operationStatusValue);
			map.put("remark", order.getRemark()==null?"":order.getRemark());
			map.put("createTime", order.getCreateTime()==null?"":sdf.format(order.getCreateTime()));
			map.put("payTime", order.getPayTime()==null?"":sdf.format(order.getPayTime()));
			map.put("sendTime", order.getSendTime()==null?"":sdf.format(order.getSendTime()));
			
			float fansOrderReward = 0f;
			List<QqbsFansOrder> qfoList = qqbsFansOrderService.selectByFansOrderId(order.getId());
			if(qfoList.size()>0){
				for(QqbsFansOrder qfo:qfoList){
					fansOrderReward += qfo.getWithdrawCash();
				}
			}
			
			float integrationAndWechatPercent = 1.6f;
			/*List<IntegrationLogEntity> ileList = nuoyaRMIService.getIntegrationListByOrderId(order.getId());
			if(ileList.size()>0){
				integrationAndWechatPercent = 5.6f;
			}*/
			
			float cashRedReward = 0f;
			if(order.getUserCashRed() == 1){
				CashRedLog crl = cashRedLogService.selectByOrderId(order.getId());
				if(crl != null){
					cashRedReward = crl.getCash();
				}
			}
			
			float leftReward = order.getTotalPrice();
			leftReward = leftReward - fansOrderReward - cashRedReward;
			leftReward = leftReward*(1-integrationAndWechatPercent/100);
			
			DecimalFormat df=new DecimalFormat("0.00");
			map.put("fansOrderReward", df.format(fansOrderReward));
			map.put("integrationAndWechatPercent", integrationAndWechatPercent);
			map.put("cashRedReward", cashRedReward);
			map.put("leftReward", df.format(leftReward));
			
			list.add(map);
		}
		
		session.setAttribute("ORDERLIST", list);
		
    	json.put("result", "0");
		json.put("description", "获取订单列表成功");
		json.put("list", list);
		json.put("count", orderListAll.size());

		return buildReqJsonObject(json);
	}
	
	@RequestMapping(value = "checkRewardAccount", method = RequestMethod.POST)
	@ResponseBody
	public String checkRewardAccount() {
		JSONObject json = new JSONObject();
		if (sign == 1) {
			json.put("result", "1");
			json.put("description", "请检查参数格式是否正确或者参数是否完整");
			return buildReqJsonInteger(1, json);
		}
		// 登录认证失败
		if (sign == 2) {
			json.put("result", "2");
			json.put("description", "账号未登录");
			return buildReqJsonInteger(2, json);
		}
		
		HttpSession session = request.getSession();
		Manager manager = (Manager) session.getAttribute("MANAGER");
        if(manager == null){
        	json.put("result", "1");
			json.put("description", "账号未登陆");
			return buildReqJsonObject(json);
        }
		
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		
		int right = 1;
		if(bodyInfo.get("accountId") == null || "".equals(bodyInfo.get("accountId"))){
			right = 0;
		}
		if(right == 0){
			json.put("result", "1");
			json.put("description", "操作失败，请检查输入的参数是否完整");
			return buildReqJsonObject(json);
		}
		
		QqbsAccount account = qqbsAccountService.selectByAccountId(bodyInfo.getInt("accountId"));
		
		String accountNickname = account==null?"":account.getNickname();
		
    	json.put("result", "0");
		json.put("description", "获取用户昵称成功");
		json.put("accountNickname", accountNickname);
		return buildReqJsonObject(json);
	}
	
	@RequestMapping(value = "sellerReward", method = RequestMethod.POST)
	@ResponseBody
	public String sellerReward() {
		JSONObject json = new JSONObject();
		if (sign == 1) {
			json.put("result", "1");
			json.put("description", "请检查参数格式是否正确或者参数是否完整");
			return buildReqJsonInteger(1, json);
		}
		// 登录认证失败
		if (sign == 2) {
			json.put("result", "2");
			json.put("description", "账号未登录");
			return buildReqJsonInteger(2, json);
		}
		
		HttpSession session = request.getSession();
		Manager manager = (Manager) session.getAttribute("MANAGER");
        if(manager == null){
        	json.put("result", "1");
			json.put("description", "账号未登陆");
			return buildReqJsonObject(json);
        }
		
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		
		int right = 1;
		if(bodyInfo.get("accountId") == null || "".equals(bodyInfo.get("accountId"))){
			right = 0;
		}else if(bodyInfo.get("orderId") == null || "".equals(bodyInfo.get("orderId"))){
			right = 0;
		}
		if(right == 0){
			json.put("result", "1");
			json.put("description", "操作失败，请检查输入的参数是否完整");
			return buildReqJsonObject(json);
		}
		
		QqbsAccount account = qqbsAccountService.selectByAccountId(bodyInfo.getInt("accountId"));
		Order order = orderService.selectByPrimaryKey(bodyInfo.getInt("orderId"));
		
		if(account == null){
			json.put("result", "1");
			json.put("description", "提现账号id不存在");
			return buildReqJsonObject(json);
		}else if(order == null){
			json.put("result", "1");
			json.put("description", "订单失效");
			return buildReqJsonObject(json);
		}else if(order != null && order.getStatus() != 4){
			json.put("result", "1");
			json.put("description", "订单不可提现");
			return buildReqJsonObject(json);
		}else if(order != null && order.getOperationStatus() == 1){
			json.put("result", "1");
			json.put("description", "订单已提现");
			return buildReqJsonObject(json);
		}
		
		if(manager.getType() == 3 && manager.getProductSellerId() != order.getSellerId()){
			json.put("result", "1");
			json.put("description", "您当前账号无权限申请该笔订单的提现，请联系客服");
			return buildReqJsonObject(json);
		}
		
		float fansOrderReward = 0f;
		List<QqbsFansOrder> qfoList = qqbsFansOrderService.selectByFansOrderId(order.getId());
		if(qfoList.size()>0){
			for(QqbsFansOrder qfo:qfoList){
				fansOrderReward += qfo.getWithdrawCash();
			}
		}
		
		float integrationAndWechatPercent = 1.6f;
		/*List<IntegrationLogEntity> ileList = nuoyaRMIService.getIntegrationListByOrderId(order.getId());
		if(ileList.size()>0){
			integrationAndWechatPercent = 5.6f;
		}*/
		
		float cashRedReward = 0f;
		if(order.getUserCashRed() == 1){
			CashRedLog crl = cashRedLogService.selectByOrderId(order.getId());
			if(crl != null){
				cashRedReward = crl.getCash();
			}
		}
		
		float leftReward = order.getTotalPrice();
		leftReward = leftReward - fansOrderReward - cashRedReward;
		leftReward = leftReward*(1-integrationAndWechatPercent/100);
		
		DecimalFormat df=new DecimalFormat("0.00");
		
		QqbsWithdrawalsLog qwl = new QqbsWithdrawalsLog();
		qwl.setAccountId(account.getAccountId());
		qwl.setWithdrawals(Float.valueOf(df.format(leftReward)));
		qwl.setStatus((byte)1);
		qwl.setCreateTime(new Date());
		qwl.setUpdateTime(new Date());
		Integer insertResult = qqbsWithdrawalsLogService.insertSelective(qwl);
		if(insertResult == 0){
			json.put("result", "0");
			json.put("description", "新增提现数据失败");
			return buildReqJsonObject(json);
		}else{
			QqbsReward qr =qqbsRewardService.selectByAccountId(account.getAccountId());
			Integer updateQr = 0;
			if(qr == null){
				qr = new QqbsReward();
				qr.setAccountId(account.getAccountId());
				qr.setAlreadyCash(0f);
				qr.setTotalReward(qwl.getWithdrawals());
				qr.setWithdrawCash(qwl.getWithdrawals());
				qr.setCreateTime(new Date());
				qr.setUpdateTime(new Date());
				updateQr = qqbsRewardService.insertSelective(qr);
			}else{
				qr.setTotalReward(qr.getTotalReward()+qwl.getWithdrawals());
				qr.setWithdrawCash(qr.getWithdrawCash()+qwl.getWithdrawals());
				updateQr = qqbsRewardService.updateByPrimaryKeySelective(qr);
			}
			
			if(updateQr == 0){
				json.put("result", "0");
				json.put("description", "reward表记录提现申请失败");
				return buildReqJsonObject(json);
			}else{
				order.setOperationStatus((byte)1);
				Integer updateOrderOperationStatus = orderService.updateOperationStatus(order);
				if(updateOrderOperationStatus == 0){
					json.put("result", "0");
					json.put("description", "修改订单提现状态失败");
					return buildReqJsonObject(json);
				}
			}
		}
		
    	json.put("result", "0");
		json.put("description", "申请提现成功");
		return buildReqJsonObject(json);
	}
}
